<!--
  @anthor: darker,
  @description: 图片/文件上传，集合图片/文件，单/多文件上传于一体,涵盖图片回显及相关动态操作 为适应不同场景提供了多个主题形式
  @date: 2020 / 07 / 17,
  @remark:
 -->
<!--
引用示例：
<uploadFile :fileList="fileList" accept="file" uploadUrl="http://whhs.zhdj360.cn/stddj-api/api/common/fileUpload/uploadBlob" :multiple="true" theme="picture-card" :fileList.sync="fileList"></uploadFile>
参数详解：
multiple ==== 是否为多文件
limit ==== 文件数量 默认为10
disabledInput ==== 开关  用户是否禁用
uploadUrl ==== 上传地址 默认为当前项目代理域名下的/stddj-api/api/common/fileUpload/uploadBlob请求接口
fileList ====  传入文件列表 用于回显
accept ==== 文件过滤  image ->> 图片类型文件  file ->> 所有文件类型
theme ==== 主题  本插件提供(text/picture/picture-card)三种模式 为匹配不同应用场景
 -->
<template>
  <div class="upload-container">
    <el-dialog
      :visible.sync="dialogVisibleImg"
      :title="ImgName"
      size="tiny"
      :append-to-body="true"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-upload
      :class="[disabledInput ? 'upLoadShowNone upload-demo' : 'upload-demo']"
      name="fileObj"
      :accept="acceptType()"
      action="string"
      :headers="myheaders"
      :multiple="multiple"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="validDoc"
      :on-preview="handlePictureCardPreview"
      :disabled="disabledInput"
      :list-type="theme"
      :http-request="httpRequest"
      :file-list="fileList"
      :limit="limit"
    >
      <i
        class="el-icon-plus avatar-uploader-icon"
        v-if="theme == 'picture-card'"
      ></i>
      <el-button v-else size="medium" icon="el-icon-upload">点击上传</el-button>
      <slot name="slot"></slot>
    </el-upload>
  </div>
</template>

<script>
var token = localStorage.getItem("token"); // 获取token
export default {
  name: "UploadFile",
  props: {
    //是否为多文件
    multiple: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 10
    },
    // 开关 是否禁用 禁用后 无法删除与上传
    disabledInput: {
      type: Boolean,
      default: false
    },
    // 文件上传地址
    uploadUrl: {
      type: String,
      default: `/api/py-common/file/upload`
      // default: `/api/py-common/dj/file/upload`,
    },
    // 文件列表 用于回显
    fileList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    // 文件过滤 image -- 图片类型文件  file -- 所有文件类型
    accept: {
      type: String,
      default: "image"
    },
    // 主题 适应不通场景 （text/picture/picture-card）
    theme: {
      type: String,
      default: "picture-card"
    },
    //控制上传图片或者文件大小
    fileSize: {
      type: Number,
      default: 20
    }
  },
  data() {
    return {
      dialogVisibleImg: false,
      ImgName: "",
      dialogImageUrl: "",
      mediaList: [
        "mp3",
        "aac",
        "mp4",
        "ape",
        "flac",
        "wav",
        "wma",
        "amr",
        "mid",
        "mp4",
        "m4v",
        "3gp",
        "mpg",
        "flv",
        "f4v",
        "swf",
        "avi",
        "gif",
        "wmv",
        "rmvb",
        "mov",
        "mts",
        "m2t",
        "webm",
        "ogg",
        "mkv"
      ], // 音视频格式，用于判断是否音视频
      myheaders: {
        Authorization: token
      },
      isUploading: null
    };
  },
  computed: {
    // 文件类型
    acceptTypeStr() {
      return (
        this.accept ||
        "doc, docx, xls, xlsx, ppt, pptx, pdf, txt, mp3, 3gp, mp4, avi"
      );
    }
  },
  methods: {
    // 匹配上传的文件类型---image/file
    acceptType() {
      if (this.accept == "image") {
        return `image/*`;
      } else if (this.accept == "pdf") {
        return `.pdf`;
      } else if (this.accept == "xls,xlsx") {
        return `.xls,.xlsx`;
      } else {
        return `.xls,.xlsx,.doc,.docx,.ppt,.pptx,.pdf,.txt,.mp3,.3gp,.mp4,.avi`;
      }
    },
    // 获取的是文件类型的文件列表
    handleSuccess(res, file, fileList) {
      let that = this;
      console.log("成功", fileList);
      const currentPic = that.$baseData.filePath + res.url;
      fileList.map((item, index) => {
        if (item.name == file.name) {
          item = {};
          item.url = currentPic;
          item.fileName = res.fileName;
        }
      });
      that.$emit("backcall", fileList);
    },
    handleRemove(file, fileList) {
      this.$emit("backcall", fileList);
    },
    // 图片预览
    handlePictureCardPreview(file) {
      let name = file.name || file.fileName;
      if (this.isImg(name)) {
        this.dialogImageUrl = file.url;
        this.dialogVisibleImg = true;
        this.ImgName = file.name;
      } else {
        window.open(file.url);
      }
    },
    // 图片/文件上传前的校验
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt10M = file.size / 1024 / 1024 < this.fileSize; //这里做文件大小限制
      if (!isLt10M) {
        this.$message({
          message: `上传文件大小不能超过 ${this.fileSize}MB!`,
          type: "error"
        });
      }
      return isLt10M;
    },
    // 上传文件之前的钩子
    validDoc(file) {
      let loc = file.name.lastIndexOf(".");
      // 截取下标加1，去掉.
      let fileType = file.name.slice(loc + 1).toLowerCase();
      console.log(fileType);
      if (this.acceptTypeStr && this.acceptTypeStr.length > 0) {
        let acceptList = this.acceptTypeStr.split(",");
        acceptList = acceptList.map(i => {
          i = i.trim();
          return i;
        });
        if (!acceptList.includes(fileType)) {
          this.$message.error(`只能上传${this.acceptTypeStr}类型的文件`);
          return false;
        }
      }
      let maxFileSize = file.size / 1024 / 1024 < this.fileSize; //这里做文件大小限制
      if (this.mediaList.indexOf(fileType) < 0) {
        // 文件最大30M
        if (!maxFileSize) {
          this.$message.error(`文件大小超出限制！限制大小为${this.fileSize}MB`);
          return false;
        }
      } else {
        // 音视频最大500M
        if (!maxFileSize) {
          this.$message.error(`文件大小超出限制！限制大小为${this.fileSize}MB`);
          return false;
        }
      }
      if (!maxFileSize) {
        this.$message.error(`文件大小超出限制！限制大小为${this.fileSize}MB`);
        return false;
      }
    },
    // 自定义上传
    httpRequest(params) {
      let that = this;
      let name = params.file.name;
      console.log("上传文件", params);
      that.$emit("nativeBackFile", params.file); //将文件返回出去
      let formData = new FormData();
      formData.append("file", params.file);
      let data = formData;
      this.isUploading = this.$loading({
        lock: true,
        text: "上传中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)"
      });
      this.$http.post(this.uploadUrl, data).then(res => {
        this.isUploading.close();
        if (res.status == 200) {
          let url = res.data.data.fileURL;
          let fileList2 = [
            {
              name,
              url
            }
          ];
          console.log("--fileList", fileList2);
          that.$emit("backcall", fileList2);
          this.$message({
            type: "success",
            message: res.data.message
          });
        }
      });
    },
    isImg(name) {
      var idx = name.indexOf(".");
      if (idx === -1) {
        console.warn("name格式不正确，请检查");
        return;
      }
      var type = name.substring(idx + 1);
      var imgArr = [
        "bmp",
        "jpg",
        "png",
        "tif",
        "gif",
        "pcx",
        "tga",
        "exif",
        "fpx",
        "svg",
        "psd",
        "cdr",
        "pcd",
        "dxf",
        "ufo",
        "eps",
        "ai",
        "raw",
        "WMF",
        "webp"
      ];
      return imgArr.indexOf(type) !== -1 ? true : false;
    }
  }
};
</script>

<style lang="less" scoped>
// rel="stylesheet/less"
/*@import "~@/styles/mixin.scss";*/
.upload-container {
  /deep/.el-upload {
    text-align: left;
  }
}
/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  background: #ddd;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  height: auto;
  max-width: inherit;
  width: auto;
}
</style>
